package com.bee.rbac.shiro;


import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.bee.admin.sys.model.User;
import com.bee.admin.sys.service.impl.UserServiceImpl;


/**
 * Created by cdyoue on 2016/10/21.
 */

public class ShiroRealm extends AuthorizingRealm {
	
    @Autowired
    private UserServiceImpl userService;
	
    private Logger logger =  LoggerFactory.getLogger(this.getClass());


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo");
        logger.info("doGetAuthorizationInfo+"+principalCollection.toString());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        
        
        System.out.println("admin");
        Set<String> roles = new HashSet<String>();
        roles.add("user");
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        logger.info("doGetAuthenticationInfo "  + authenticationToken.toString());
//        System.out.println("doGetAuthenticationInfo,"+ authenticationToken.toString());

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
//        System.out.println(token.getPassword());
//        System.out.println(token.getCredentials());
//        
        
        User user = userService.getUser(userName);
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user", user);
//        System.out.println(user.getPassword());
        return new SimpleAuthenticationInfo(userName,user.getPassword(),ByteSource.Util.bytes("rg"),getName());
//        return null;
    }

}
